<?php
if (!init()) {
  redirect('?action=login');
}

include_once("functions/utils/ImageUtil.php");

$uploaddir = getcwd() . \controller\Config::getPropertyByKey('directory.topic.comment');

$acceptedFormats = array('gif', 'png', 'jpg', 'jpeg');


$timeStamp = getLocalTimeStamp();

$date = f_Date($timeStamp);
$time = f_Time($timeStamp);

$resultSet = createTopicComment($_POST['tid'], $_POST['content'], f_Date($timeStamp), f_Time($timeStamp), $_POST['reply']);

$readResultSet = updateUserTopicRead($_POST['tid']);

if (isset($_FILES['images'])) {

  $i = 0;
  $lastInsertRespImgId = 0;

  $uploadfile = '';

  while (isset($_FILES['images']['name'][$i])) {

    if (in_array(strtolower(pathinfo($_FILES['images']['name'][$i], PATHINFO_EXTENSION)), $acceptedFormats)) {
      $file = date("dmY") . "_" . date("GHi") . getFormattedTime() . "_com_img" . "." . pathinfo($_FILES['images']['name'][$i], PATHINFO_EXTENSION);

      $uploadfile = $uploaddir . $file;

      if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $uploadfile)) {
        \util\ImageUtil::createImagePreview($uploadfile, 200, 'preview/topic_img_preview', 'topic_img');
        $imgResultSet = addNewTopicCommentImage($file, $date, $time);
      }
    }
    $i++;
  }

}
$initiatorAction = \controller\ControllerUtil::getEncodedActionFromUrlWithParameters($_SERVER['HTTP_REFERER']);

if ($resultSet) {
  increaseUsersMessages();
  redirect("?action=msg&header=header.topic.comment.success&body=body.topic.comment.success&view=" . $initiatorAction);
} else {
  redirect("?action=msg&header=header.topic.comment.failed&body=body.topic.comment.failed&view=" . $initiatorAction);
}

